import React, { Fragment } from 'react'
import {
  StyleSheet,
  View,
  Text,

  ScrollView,
  Image
} from 'react-native'
import Picker from 'react-native-picker'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import CustomButton from 'src/components/button/CustomButton'
import CustomInputLabel from 'src/components/button/CustomInputLabel'
import showPicker from 'src/utils/PickerUtil'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_SAVEUSERINFO_B_ACTION
} from 'src/store/actions/userinfo'
import { getGenderChinese } from 'src/utils/ConfigUtil'
import { showModal } from 'src/utils/ModalUtil'
import GenderChoice from 'src/components/modal/GenderChoice'
import { keywordBlock } from 'src/utils/RegUtil'

const year = new Date().getFullYear()
const years = new Array(100).fill(0).map((e, i) => `${year - i}年`)
// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  doRequestSaveUserInfoToB (payload) {
    const promise = DO_REQUEST_SAVEUSERINFO_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo }) => {
    return {
      userId: userinfo.userId,
      userinfoB: userinfo.B
    }
  },
  mapDispatchToProps
)
class BUserInfoBasic extends BasePage {
  constructor (props) {
    super(props)
    const { userName, gender, gmtBorth, mobile, postion } = this.props.userinfoB
    this.state = {
      header: {},
      userName,
      gender,
      gmtBorth: gmtBorth ? gmtBorth.split('-')[0] : null,
      mobile,
      postion,
      saveEnable: false
    }
  }

  childRender () {
    const { userName, gender, gmtBorth, mobile, postion } = this.state
    return (
      <Fragment>
        <ScrollView style={styles.container} contentContainerStyle={styles.contentScrollView}>
          <Text style={styles.messageTitleTopDesc}>基本信息</Text>
          <Text style={styles.messageTitleBottom}>
            *完善个人信息能更快的找到心仪的工作
          </Text>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              height: ScaleS(230),
              marginTop: ScaleS(34)
            }}
          >
            <CustomInputLabel
              title="姓名"
              value={userName}
              placeHolder="请输入"
              onPress={this._nameFieldClick}
            />
            <CustomInputLabel
              title="性别"
              value={getGenderChinese(gender)}
              placeHolder="请选择"
              onPress={this._genderFieldClick}
            />
            <CustomInputLabel
              title="出生年份"
              value={gmtBorth}
              placeHolder="请选择"
              last={true}
              onPress={this._birthFieldClick}
            />
          </CustomBoxShadow>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              marginTop: ScaleS(30),
              shadowRadius: ScaleS(30)
            }}
          >
            <CustomInputLabel
              title="职务"
              value={postion}
              placeHolder={'请输入'}
              onPress={this._postionFieldCLick}
            />
            <CustomInputLabel
              title="手机号"
              value={mobile}
              placeHolder={'请输入'}
              last={true}
              onPress={this._phoneFieldCLick}
            />
          </CustomBoxShadow>
        </ScrollView>
      </Fragment>
    )
  }

  renderNavigationBarChild = () => {
    const { saveEnable } = this.state
    return (
      <CustomButton
        style={styles.saveBtnWrap}
        onPress={this._saveButtonClick}
      >
        <Text
          style={[styles.saveButton, saveEnable && styles.saveButtonEnable]}
        >
          保存
        </Text>
      </CustomButton>
    )
  }

  componentDidMount () {}

  static getDerivedStateFromProps (props, state) {
    console.log('getDerivedStateFromProps', state)
    return BUserInfoBasic.saveButtonEnable(state)
  }

  static saveButtonEnable (state) {
    const { userName, gender, gmtBorth, mobile, postion } = state
    const saveEnable = !!(userName && gender && gmtBorth && mobile && postion)
    if (state.saveEnable !== saveEnable) {
      console.log('saveEnable change', saveEnable)
      return {
        saveEnable
      }
    }
    return null
  }

  _nameFieldClick = () => {
    const saveCallback = userName => {
      this.setState({
        userName
      })
    }
    const { userName: value } = this.state
    this.props.navigation.navigate('CommonInputPage', {
      title: '姓名',
      blockReg: keywordBlock.value,
      desc: '*请填写真实姓名',
      placeholder: '请输入姓名',
      value,
      maxLength: 6,
      saveCallback
    })
  }

  /**
   * 性别选择
   * @param type male boy ;female girl
   */
  _genderFieldClick = () => {
    const { gender } = this.state
    const config = {
      gender,
      onConfirm: this.genderConfirm
    }
    this.genderModal = showModal(<GenderChoice {...config}/>)
  }

  genderConfirm = (gender) => {
    this.genderModal && this.genderModal.close()
    this.setState({
      gender
    })
  }

  _birthFieldClick = () => {
    const { gmtBorth } = this.state
    const pickerData = years
    const selectedValue = [`${gmtBorth || year - 18}年`]
    const pickerTitleText = '选择出生年份'
    showPicker({
      pickerData,
      selectedValue,
      pickerTitleText,
      onConfirm: ([gmtBorth]) => {
        this.setState({
          gmtBorth: gmtBorth.replace(/年/, '')
        })
      }
    })
  }

  _postionFieldCLick = () => {
    const saveCallback = postion => {
      this.setState({
        postion
      })
    }
    const { postion: value } = this.state
    this.props.navigation.navigate('CommonInputPage', {
      title: '我的职务',
      desc: '*公司组织架构的岗位名称',
      placeholder: '请输入职位名称',
      value,
      maxLength: 8,
      saveCallback
    })
  }

  _phoneFieldCLick = () => {
    const callback = mobile => {
      this.setState({
        mobile
      })
    }
    this.props.navigation.navigate('CommonChangePhone', {
      callback
    })
  }

  /**
   * 保存
   */
  _saveButtonClick = () => {
    const { saveEnable, userName, gmtBorth, gender, mobile, postion } = this.state
    if (!saveEnable) {
      CommonToast('请修改或完善信息后提交')
      return
    }
    const {
      userId,
      userinfoB: { id }
    } = this.props
    const params = {
      userName,
      gmtBorth: `${gmtBorth}-01-01 00:00:00`,
      gender,
      mobile,
      userId,
      postion,
      id
    }
    ShowLoading()
    this.props
      .doRequestSaveUserInfoToB({ params })
      .then(res => {
        console.log('doRequestSaveUserInfoToB', res)
        this.goBack()
      })
      .finally(() => {
        DismissLoading()
      })
  }
}

export default BUserInfoBasic

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF'
  },
  contentScrollView: {
    paddingBottom: ScaleS(50)
  },
  maskView: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    backgroundColor: '#00000055',
    zIndex: 101
  },
  messageTitleTopDesc: {
    marginHorizontal: ScaleS(20),
    marginTop: ScaleS(10),
    fontSize: ScaleT(27),
    lineHeight: ScaleS(47),
    fontWeight: 'bold',
    color: '#444444'
  },
  messageTitleBottom: {
    marginHorizontal: ScaleS(20),
    fontSize: ScaleT(12),
    lineHeight: ScaleS(28),
    color: '#FFC200'
  },

  infoViewShadow: {
    width: ScaleS(335),
    shadowColor: '#9C9C9C',
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.25,
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    },
    backgroundColor: 'white',
    borderRadius: ScaleS(10),
    marginHorizontal: ScaleS(20),
    paddingHorizontal: ScaleS(16)
  },
  genderView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  genderItemView: {},
  genderItemSelected: {
    backgroundColor: '#000000'
  },
  genderItemDefault: {
    backgroundColor: '#F0F0F0'
  },
  genderItem: {
    width: ScaleS(27),
    height: ScaleS(31)
  },
  genderVerticalLine: {
    marginHorizontal: ScaleS(20),
    width: ScaleS(1),
    height: ScaleS(16),
    backgroundColor: '#D2D2D2'
  },
  nextButton: {
    position: 'absolute',
    bottom: ScaleS(20),
    left: ScaleS(32)
  },
  saveBtnWrap: {
    alignSelf: 'flex-end',
    marginRight: ScaleS(20)
  },
  saveButton: {
    fontSize: ScaleT(16),
    fontWeight: '400',
    color: '#bbbbbb'
  },
  saveButtonEnable: {
    color: '#000000'
  }
})
